
import { Storage } from "@/constants/storage";
import { setStorageSync, getStorageSync } from '@tarojs/taro'
import { fetchUserInfo } from "@/service/login";
import { UserInfo } from "@/service/type";
import { createContext, useCallback, useState } from "react";

export interface AppState {
  /**用户信息 */
  userInfo: UserInfo;
  /**小程序初始化状态 */
  isInitialized: boolean;
}

export interface AppAction {
  update: (data: Partial<AppState>) => void;
  refresh: () => void;
}

const defaultAppStateValue = {
  userInfo: (getStorageSync(Storage.USER_INFO) || {}) as UserInfo,
  isInitialized: false
}

const AppContext = createContext<AppState>(defaultAppStateValue)

export const AppActionContext = createContext<AppAction>({
  update() { },
  refresh() { }
})

export function useAppData() {
  const [contextValue, setContextValue] = useState<AppState>(defaultAppStateValue)

  const updateContextValue = useCallback((data: Partial<AppState>) => {
    //TODO Object.assign()是浅拷贝，setContextValue不会触发视图更新
    setContextValue({ ...contextValue, ...data })
  }, [setContextValue])

  const refresh = useCallback(async () => {
    const { res } = await fetchUserInfo()
    if (res) {
      setStorageSync(Storage.USER_INFO, res)
      updateContextValue({
        ...createContext,
        isInitialized: true,
        userInfo: res,
      })
    }
  }, [updateContextValue])

  return [contextValue, { update: updateContextValue, refresh }] as const
}


export default AppContext